const dayjs = require('dayjs')
const db = require('../db/index')
const createExcel = require('../js/exceljs')
const { recognitionImgQualit } = require('./recognitionImg')
const os = require('os')
const express = require('express')
const app = express()
// 获取发货记录
exports.deliverList = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  const sql = `select * from deliver where appid=? limit ${size} OFFSET  ${from}`
  db.query(sql, [appid], (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from deliver where appid=? `
    db.query(sql2, [appid], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 删除发货记录
exports.deliverListDelete = (req, res) => {
  let data = req.body
  let sql = `delete from deliver where _id=?`
  db.query(sql, [data.id], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      message: '删除成功',
      type: 1
    })
  })
}
// 导出发货记录
exports.deliverListCreateExcel = (req, res) => {
  let data = req.body
  columns = [
    { header: '发货时间', key: 'create_time' },
    { header: '产品类型', key: 'filmType' },
    { header: '产品名称', key: 'filmName' },
    { header: '产品数量', key: 'number' },
    { header: '发货门店', key: 'colorAlterationNumber' },
    { header: '联系方式', key: 'phone' },
    { header: '负责人', key: 'linkman' },
    { header: '收货门店', key: 'storeName' },
    { header: '质保编号', key: 'filmNo' },
    { header: '质保年限', key: 'filmAge' },
    { header: '贴膜次数', key: 'count' },
    { header: '状态', key: 'deliverStatus' }
  ]
  let sql = ``
  if (data.id == 'all') {
    sql = 'select * from deliver where appid=?'
  } else {
    sql = 'select * from deliver where appid=? and _id in (?)'
  }
  db.query(sql, [data.appid, data.id], async (err, res2) => {
    if (err) return res.cc(err)
    res2.forEach((item) => {
      item.create_time = dayjs(item.create_time).format('YYYY-MM-DD HH:mm:ss')
      if (item.deliverStatus == 0) {
        item.deliverStatus = '待签收'
      } else if (item.deliverStatus == 1) {
        item.deliverStatus = '已签收'
      } else {
        item.deliverStatus = '已拒收'
      }
    })
    const buffer = await createExcel.createExcel(columns, res2)
    res.setHeader('Content-disposition', 'attachment; filename=file.xlsx')
    res.setHeader('Content-type', 'application/octet-stream')
    res.send(buffer)
  })

}
// 发货记录条件查询
exports.deliverListSerach = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  pageData.storeName = pageData.storeName ? pageData.storeName : ''
  pageData.linkman = pageData.linkman ? pageData.linkman : ''
  pageData.filmNo = pageData.filmNo ? pageData.filmNo : ''
  pageData.phone = pageData.phone ? pageData.phone : ''
  pageData.create_time = pageData.create_time ? pageData.create_time : ''
  pageData.filmType = pageData.filmType ? pageData.filmType : ''
  pageData.filmName = pageData.filmName ? pageData.filmName : ''
  pageData.deliverStatus = pageData.deliverStatus?.length > 0 ? pageData.deliverStatus : ['0', '1', '2']
  const sql = `select * from deliver where appid=${appid}   and (storeName like "%${pageData.storeName}%" and linkman like "%${pageData.linkman}%" and filmNo like "%${pageData.filmNo}%" and phone like "%${pageData.phone}%" and create_time like "%${pageData.create_time}%"and filmType like "%${pageData.filmType}%"and filmName like "%${pageData.filmName}%") and deliverStatus in (?) limit ${size} OFFSET  ${from}`
  db.query(sql, [pageData.deliverStatus], (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from deliver where appid=? and (storeName like "%${pageData.storeName}%" and linkman like "%${pageData.linkman}%" and filmNo like "%${pageData.filmNo}%" and phone like "%${pageData.phone}%" and create_time like "%${pageData.create_time}%"and filmType like "%${pageData.filmType}%"and filmName like "%${pageData.filmName}%") and deliverStatus in (?)`
    db.query(sql2, [appid, pageData.deliverStatus], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 查看质保信息列表
exports.qualityList = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  let sql = `select * from quality where appid=? and status=?  limit ${size} OFFSET  ${from}`
  let sql2 = `select count(*) from quality where appid=? and status=?`
  if (pageData.status == 0) {
    sql = `select * from quality where appid=? and (status=0 or status=2)  limit ${size} OFFSET  ${from}`
    sql2 = `select count(*) from quality where appid=? and (status=0 or status=2)`
  }
  db.query(sql, [appid, pageData.status], (err, res2) => {
    if (err) return res.cc(err)
    db.query(sql2, [appid, pageData.status], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 小程序根据条件查询质保信息
exports.qualityListSmall = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  let sql = `select * from quality where appid=? and (ownerName= ? or ownerPhone = ? or carNo= ? or carVIN = ? or filmNo = ?) and status=? limit ${size} OFFSET  ${from}`
  db.query(sql, [appid, pageData.sherchData, pageData.sherchData, pageData.sherchData, pageData.sherchData, pageData.sherchData, pageData.status], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2,
    })
  })
}
// 获取质保详情所有的记录
exports.qualityDetilsListSmall = (req, res) => {
  let pageData = req.body
  let sql = `select * from quality where appid=? and carId=?`
  let sql2 = `select count(*) from quality where appid=? and carId=?`
  db.query(sql, [pageData.appid, pageData.carId], (err, res2) => {
    if (err) return res.cc(err)
    db.query(sql2, [pageData.appid, pageData.carId], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 获取质保详情
exports.qualityDetilsSmall = (req, res) => {
  let pageData = req.body
  let sql = `select * from quality where appid=? and _id=?`
  db.query(sql, [pageData.appid, pageData._id], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2,
    })
  })
}
// 获取相同车牌号与车架号的质保
exports.qualityDetilsSmallAll = (req, res) => {
  let pageData = req.body
  let sql = `select * from quality where appid=? and carNo=? and carVIN=? and ownerName=? and ownerPhone=? and status=1`
  let sql2 = `select * from store where _id=?`
  db.query(sql, [pageData.appid, pageData.carNo, pageData.carVIN, pageData.ownerName, pageData.ownerPhone], (err, res2) => {
    if (err) return res.cc(err)
    if (res2.length > 0) {
      res2.forEach((item) => {
        db.query(sql2, [item._id], (err, res3) => {
          if (res3.length > 0) {
            item.linkman = res3[0].linkman
          }
        })
      })

    }
    res.send({
      res: res2,
    })
  })
}
// 添加质保
exports.qualityListAdd = (req, res) => {
  let data = req.body
  data.status = 0
  data.imgList = JSON.stringify(data.imgList)
  data.timeOfReceipt = JSON.stringify(data.timeOfReceipt)
  let sql = `select * from deliver where appid=? and filmNo=?`
  db.query(sql, [data.appid, data.filmNo], (err, res4) => {
    if (err) return res.cc(err)
    if (res4.length > 0 && res4[0].count > 0) {
      let storeSql = `select * from store where _id=?`
      db.query(storeSql, [data.storeId], (err, res3) => {
        if (err) return res.cc(err)
        console.log(res3[0])
        data.storeWorkName = res3[0].name
        const sql2 = `insert into quality set ?`
        db.query(sql2, data, (err, res2) => {
          if (err) return res.cc(err)
          const deliverSubtract = `update deliver set count=?,useCount=? where _id=?`
          console.log(res4[0])
          db.query(deliverSubtract, [res4[0].count - 1, res4[0].useCount + 1, res4[0]._id], (err, res4) => {
            if (err) return res.cc(err)
            res.send({
              message: '提交成功待审核',
              type: 1
            })
          })
        })
      })
    } else {
      res.send({
        message: '编号使用次数不足',
        type: 0
      })
    }
  })
}
// 添加质保不图片识别
exports.qualityListAddNo = (req, res) => {
  let data = req.body
  data.status = 0
  data.imgList = JSON.stringify(data.imgList)
  let sql = `select * from deliver where appid=? and filmNo=?`
  db.query(sql, [data.appid, data.filmNo], (err, res3) => {
    if (err) return res.cc(err)
    if (res3.length > 0 && res3[0].count > 0) {
      console.log(res3[0]._id)
      const sql2 = `insert into quality set ?`
      db.query(sql2, data, (err, res2) => {
        if (err) return res.cc(err)
        const deliverSubtract = `update deliver set count=?,useCount=? where _id=?`
        db.query(deliverSubtract, [res3[0].count - 1, res3[0].useCount + 1, res3[0]._id], (err, res4) => {
          if (err) return res.cc(err)
          res.send({
            message: '提交成功待审核',
            type: 1
          })
        })

      })
    } else {
      res.send({
        message: '编号使用次数不足',
        type: 0
      })
    }
  })


}
// 上传质保小程序
exports.qualityListAddSmall = (req, res) => {
  let data = req.body
  let regex = ''
  const interfaces = os.networkInterfaces()
  for (const iface of Object.values(interfaces)) {
    for (const config of iface) {

      if (config.family === 'IPv4' && config.internal) {
        regex = `http://${config.address}:3008`
      }
    }
  }
  let imgList = JSON.parse(JSON.stringify(data.imgList))

  let imgListText = []
  imgList.forEach((item, index) => {
    item.img = item.img.replace(regex, "public")
    setTimeout(async () => {
      const res = await recognitionImgQualit(item.img)
      imgListText.push(JSON.parse(res).words_result)
    }, index * 600)
  })
  setTimeout(() => {

    try {
      let imgTextAll = {}
      imgListText.forEach((item, index) => {
        imgTextAll[index] = []
        item.forEach((item2) => {
          imgTextAll[index].push(item2.words)
        })
      })
      for (const key in imgTextAll) {
        imgTextAll[key] = imgTextAll[key].reduce((acc, cur) => acc + cur, '')
        if (key == 0) {
          if (imgTextAll[key].indexOf(data.storeWorkName) == -1) {
            throw `门店图片信息与填写不一致`
          }
        } else if (key == 1 && data.carNo != '新车未上牌') {
          if (imgTextAll[key].indexOf(data.carNo) == -1) {
            throw `拍照图片信息与填写不一致`
          }
        } else if (key == 2) {
          if (imgTextAll[key].indexOf(data.filmNo) == -1) {
            throw `膜卷号图片信息与填写不一致`
          }
        } else if (key == 3) {
          if (imgTextAll[key].indexOf(data.carVIN) == -1) {
            throw `车架号图片信息与填写不一致`
          }
        } else if (key == 4) {
          if (imgTextAll[key].indexOf(data.batchNumber) == -1) {
            throw `批号图片信息与填写不一致`
          }
        }
      }
      data.status = 1
      data.imgList = JSON.stringify(data.imgList)
      let sql = `select * from deliver where appid=? and filmNo=?`
      db.query(sql, [data.appid, data.filmNo], (err, res3) => {
        if (err) return res.cc(err)
        if (res3.length > 0 && res3[0].count > 0) {
          const sql2 = `insert into quality set ?`
          db.query(sql2, data, (err, res2) => {
            if (err) return res.cc(err)
            const deliverSubtract = `update deliver set count=?,useCount=? where _id=?`
            db.query(deliverSubtract, [res3[0].count - 1, res3[0].useCount + 1, res3[0]._id], (err, res4) => {
              if (err) return res.cc(err)
              res.send({
                message: '添加成功',
                type: 1
              })
            })

          })

        } else {
          res.send({
            message: '编号使用次数不足',
            type: 0
          })
        }
      })

    } catch (error) {
      res.send({
        message: error,
        type: 0
      })
    }

  }, 3000)
}

// 获取膜的型号
exports.filmNameListAll = (req, res) => {
  let data = req.body
  const sql2 = `select * from film where appid=? and type=?`
  db.query(sql2, [data.appid, data.type], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      res: res2,
    })

  })
}
// 根据质保编号获取信息
exports.qualitNumberDetils = (req, res) => {
  let data = req.body
  const sql2 = `select * from deliver where filmNo = ? and appid=?`
  db.query(sql2, [data.filmNo, data.appid], (err, res2) => {
    if (err) return res.cc(err)
    if (res2.length > 0) {
      res.send({
        res: res2[0],
        type: 1
      })
    } else {
      res.send({
        message: '质保编号不存在',
        type: 2
      })
    }

  })
}
// 导出质保记录
exports.QualityCreateExcel = (req, res) => {
  let data = req.body
  columns = [
    { header: '质保上传时间', key: 'workTime' },
    { header: '产品类型', key: 'filmType' },
    { header: '产品名称', key: 'filmName' },
    { header: '施工门店', key: 'storeWork' },
    { header: '车主姓名', key: 'ownerName' },
    { header: '联系方式', key: 'ownerPhone' },
    { header: '车牌号', key: 'carNo' },
    { header: '车架号', key: 'carVIN' },
    { header: '施工部位', key: 'carApart' },
    { header: '质保年限', key: 'filmAge' }
  ]
  let sql = ``
  if (data.id == 'all') {
    sql = 'select * from quality where appid=? and status= 1'
  } else {
    sql = 'select * from quality where appid=? and _id in (?)'
  }
  db.query(sql, [data.appid, data.id], async (err, res2) => {
    if (err) return res.cc(err)
    res2.forEach((item) => {
      item.workTime = dayjs(item.workTime).format('YYYY-MM-DD HH:mm:ss')
    })
    const buffer = await createExcel.createExcel(columns, res2)
    res.setHeader('Content-disposition', 'attachment; filename=download.xlsx')
    res.setHeader('Content-type', 'application/octet-stream')
    res.send(buffer)
  })

}
// 导出待审核质保记录
exports.QualityCreateExcel2 = (req, res) => {
  let data = req.body
  columns = [
    { header: '质保上传时间', key: 'workTime' },
    { header: '产品类型', key: 'filmType' },
    { header: '产品名称', key: 'filmName' },
    { header: '施工门店', key: 'storeWork' },
    { header: '车主姓名', key: 'ownerName' },
    { header: '联系方式', key: 'ownerPhone' },
    { header: '车牌号', key: 'carNo' },
    { header: '车架号', key: 'carVIN' },
    { header: '施工部位', key: 'carApart' },
    { header: '质保年限', key: 'filmAge' }
  ]
  let sql = ``
  if (data.id == 'all') {
    sql = 'select * from quality where appid=? and (status=1 or status=2) '
  } else {
    sql = 'select * from quality where appid=? and _id in (?)'
  }
  db.query(sql, [data.appid, data.id], async (err, res2) => {
    if (err) return res.cc(err)
    res2.forEach((item) => {
      item.workTime = dayjs(item.workTime).format('YYYY-MM-DD HH:mm:ss')
    })
    const buffer = await createExcel.createExcel(columns, res2)
    res.setHeader('Content-disposition', 'attachment; filename=download.xlsx')
    res.setHeader('Content-type', 'application/octet-stream')
    res.send(buffer)
  })

}
// 质保查询
exports.qualitySerach = (req, res) => {
  let pageData = req.body
  let page = pageData.page * 1 - 1
  let size = pageData.size * 1
  let from = page * size
  let appid = pageData.appid
  pageData.storeWorkName = pageData.storeWorkName ? pageData.storeWorkName : ''
  pageData.carName = pageData.carName ? pageData.carName : ''
  pageData.carVIN = pageData.carVIN ? pageData.carVIN : ''
  pageData.filmNo = pageData.filmNo ? pageData.filmNo : ''
  pageData.ownerName = pageData.ownerName ? pageData.ownerName : ''
  pageData.workTime = pageData.workTime ? pageData.workTime : ''
  pageData.ownerPhone = pageData.ownerPhone ? pageData.ownerPhone : ''
  pageData.filmName = pageData.filmName ? pageData.filmName : ''

  const sql = `select * from quality where appid=${appid}  and (storeWorkName like "%${pageData.storeWorkName}%" and carName like "%${pageData.carName}%" and carVIN like "%${pageData.carVIN}%" and filmNo like "%${pageData.filmNo}%" and ownerName like "%${pageData.ownerName}%"and workTime like "%${pageData.workTime}%"and ownerPhone like "%${pageData.ownerPhone}%"  and filmName like "%${pageData.filmName}%") and status=? limit ${size} OFFSET  ${from}`
  db.query(sql, [pageData.status], (err, res2) => {
    if (err) return res.cc(err)
    let sql2 = `select count(*) from quality where appid=? and (storeWorkName like "%${pageData.storeWorkName}%" and carName like "%${pageData.carName}%" and carVIN like "%${pageData.carVIN}%" and filmNo like "%${pageData.filmNo}%" and ownerName like "%${pageData.ownerName}%"and workTime like "%${pageData.workTime}%"and ownerPhone like "%${pageData.ownerPhone}%"  and filmName like "%${pageData.filmName}%") and status=? `
    db.query(sql2, [appid, pageData.status], (err2, res3) => {
      if (err2) return res.cc(err2)
      res.send({
        res: res2,
        total: res3[0]['count(*)']
      })
    })
  })
}
// 修改状态
exports.qualitChangeStatus = (req, res) => {
  let data = req.body
  let sql = `update quality set status=?,idea=? where _id=?`
  db.query(sql, [data.status, data.idea, data._id], (err, res2) => {
    if (err) return res.cc(err)
    res.send({
      message: "审核完成",
      type: 1
    })
  })
}